package cn.hsw.platform.exception;

import cn.hsw.platform.core.doc.exception.CheckPermissionException;
import cn.hsw.platform.core.doc.exception.NotFoundException;
import cn.hsw.platform.core.enums.HttpEnum;
import cn.hsw.platform.core.util.MapUtil;
import cn.hsw.platform.core.util.ResultUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

/**
 * gateway统一异常处理
 * @author 李子木
 * @date 2020-12-07
 */
public class ExceptionHandler extends DefaultErrorWebExceptionHandler {

    Log log = LogFactory.get();
    public ExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    /**
     * 修改异常返回处理为json
     * @param errorAttributes -
     * @return -
     */
    @Override
    protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
    }

    @Override
    protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {
        return HttpStatus.OK;
    }

    @Override
    protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        int code = 500;

        //拿到异常信息
        Throwable error = super.getError(request);
        String message = error.getMessage();
        log.error("gateway网关统一拦截：{}",error.getMessage(),error);
        /*这里判断对象的exception 然后进行处理*/
        if (error instanceof ResponseStatusException) {
            final HttpStatus status = ((ResponseStatusException) error).getStatus();
            code = status.value();
            message = status.name();
        }else if(error instanceof CheckPermissionException){
            code = HttpEnum.UNAUTHORIZED.getCode();
        }else if(error instanceof NotFoundException){
            code = ((NotFoundException) error).getCode();
        }
        try {
            return MapUtil.of(ResultUtil.error(code,message));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }
}
